#include <iostream>
#include <cstring>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>

int main(int num, char *args[])
{
    if (num != 3)
    {
        std::cout << "./tcpclient serverip serverprot" << std::endl;
        exit(1);
    }

    // 填充服务器字段
    struct sockaddr_in server;
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(args[1]);
    server.sin_port = htons(std::stoi(args[2]));
    socklen_t len = sizeof(server);
    while (true)
    {
        // 申请套接字
        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            std::cout << "socket errno:" << errno << ",strerror:" << strerror(errno);
            exit(2);
        }

        // 本地缓冲内容
        std::string str;
        do
        {
            std::cout << "请输入要查找的单词:";
            std::getline(std::cin, str);
        } while (str.empty());

        // 申请连接,cnt为最大重连数
        int cnt = 10;
        while (--cnt)
        {
            if (connect(sockfd, (const sockaddr *)(&server), len))
            {
                std::cout << "连接失败,正在重连..." << std::endl;
                sleep(2);
            }
            else
                break;
        }

        if (cnt == 0)
        {
            std::cout << "重连失败,退出客户端" << std::endl;
            exit(3);
        }

        if (write(sockfd, str.c_str(), str.size()) < 0)
        {
            std::cout << "发送失败" << std::endl;
            close(sockfd);
            continue;
        }

        char buf[4090];
        int n = read(sockfd, buf, sizeof(buf));
        if (n < 0)
        {
            std::cout << "读取失败" << std::endl;
        }
        else
        {
            std::cout << buf << std::endl;
        }

        close(sockfd);
    }

    return 0;
}